package com.example.service;

import com.example.entity.Course;
import com.example.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class StudentService {

    // 1. Field注入方式
    @Autowired
    private CourseService fieldInjectedCourseService;

    // 2. Set注入方式 - 先声明变量
    private CourseService setInjectedCourseService;

    // 3. 构造方法注入方式 - 先声明变量
    private CourseService constructorInjectedCourseService;

    private Map<Integer, Student> students;

    @Autowired
    public StudentService(CourseService constructorInjectedCourseService) {
        this.constructorInjectedCourseService = constructorInjectedCourseService;
        // 初始化学生数据
        students = new HashMap<>();
        students.put(1, new Student(1, "张三"));
        students.put(2, new Student(2, "李四"));
    }

    @Autowired
    public void setSetInjectedCourseService(CourseService setInjectedCourseService) {
        this.setInjectedCourseService = setInjectedCourseService;
    }

    // 选课功能
    public void selectCourse(int studentId, int courseId) {
        // 使用 constructorInjectedCourseService 实现选课逻辑
        Student student = students.get(studentId);
        if (student == null) {
            System.out.println("学生不存在");
            return;
        }

        Course course = constructorInjectedCourseService.getCourseById(courseId);
        if (course == null) {
            System.out.println("课程不存在");
            return;
        }

        student.getSelectedCourses().add(course);
        System.out.println(student.getName() + " 选择了 " + course.getName());
    }
}